//
// C++ Implementation: Product
//
// Description: this class stores details on a product by being fed from a file
//
//
// Author:  <>, (C) 2007
//
//
//

#include "Product.h"

//fills the product with the given info
//if the name is not provided or "", isUndefined is set to true
Product::Product ( string name, float BuyingPrice, float SellingPrice ,int quantity ) :name ( name ),BuyingPrice ( BuyingPrice ),SellingPrice ( SellingPrice),quantity ( quantity ), isUndefined ( name=="" )
{
}

//calculates the profit that would be earned if all the stocks for this product were sold
float Product::getPredictedProfit ()
{
	return quantity*(SellingPrice - BuyingPrice);
}


//loads product info from a filestream using the latter's position in file to eat the first product
//note: the filestream's get pointer is moved when a product is "eaten"
//note: if no could be found, the Product is set as undefined (which can be tested with bool operator)
Product::Product ( istream& filestream )
{
	string tmp;
	float f;
	int i;
	//note : we don't care about end of file checkings, because getline() returns directly when there's EOF found
	getline(filestream,tmp); //name
	if(tmp.length() > 0)
	{
		name = tmp;
		isUndefined = false;
		getline(filestream,tmp); //buy price
		stringstream a(tmp);
		if(a >> f)
		{
			BuyingPrice = f;
		
			getline(filestream,tmp); //sell price
			stringstream b(tmp);
			if(b >> f)
			{
				SellingPrice = f;
			
				getline(filestream,tmp); //quantity
				stringstream c(tmp);
				if(c >> i)
				{
					quantity = i;
				}//else : well there will be no quantity for this ! (it will have a default value 0)
			}//else : we don't fill things further
		}//else : we don't fill things further
	}//else: this Product doesn't even have a name: this object is undefined and must be checked
	else
		isUndefined = true;
}








/* You can do if(someProductInstance) on the object thanks to this */
Product::operator bool() const    
// true/false whether this object contains any information about a product or nothing
{
	return !isUndefined;
}









//lets us do cout << someProductInstance, which prints the latter's details nicely
ostream& operator<< ( ostream& out, Product& prod )
{
#define endWidth 30
	out << setfill(' ');
	out << "<Product>" << endl;
	out << "  name            :" << setw ( endWidth ) << ( prod.name!="" ? prod.name: "none" ) << endl;
	out << "  buying price    :" << setw ( endWidth-1 ) << prod.BuyingPrice << "$" << endl;
	out << "  selling price   :" << setw ( endWidth-1 ) << prod.SellingPrice << "$" << endl;
	out << "  quantity        :" << setw ( endWidth ) << prod.quantity << endl;
	out << "</Product>" << endl;

	return out;
}


